let { Service } = require('egg')
const user = require('../contract/user')
const Base64 = require('../utils/Base64')
class UserService extends Service {
  // 登录
  async login(user) {
    // console.log(Base64);
    let base64 = new Base64()
    let { mysql } = this.app
    let { account, password } = user
    let accountInfo = await mysql.get('user', { account })
    if (accountInfo) {


      if (accountInfo.password == password) {
        // 获取用户信息
        let { userId, roleId } = accountInfo
        let obj = {}
        if (roleId == 0) {
          let admin = await mysql.get('admin', { adminId: userId })
          obj.id = admin.adminId
          obj.name = admin.admName
          obj.age = admin.admAge
          obj.gender = admin.admGender
        } else if (roleId == 1) {
          let teacher = await mysql.get('teacher', { teacherId: userId })
          obj.id = teacher.teacherId
          obj.name = teacher.teachName
          obj.age = teacher.teachAge
          obj.gender = teacher.teaGender
        } else if (roleId == 2) {
          let student = await mysql.get('student', { studentId: userId })
          obj.id = student.studentId
          obj.name = student.stuName
          obj.age = student.stuAge
          obj.gender = student.stuGender
        }else if(roleId==-1){
          obj.id = -1,
          obj.name="正义",
          obj.age = 0,
          obj.gender = "男"
        }

        return {
          accountInfo,
          user: obj,
          message: "登录成功"
        }
      } else {
        return {
          message: "密码错误"
        }
      }
    } else {
      return {
        message: "该账号不存在"
      }
    }
  }
  // 注册
  async register(user) {

    let { mysql } = this.app
    let { account, password, avatar, roleId, nickName, userId, mobile } = user
    // 最先做一个账号唯一性判断
    let onlyAcc = await mysql.get('user', { account })
    // console.log(onlyAcc);
    if (onlyAcc) {
      return "该账号已存在，请重新设置"
    }
    // 设置默认头像
    if (!avatar) {
      avatar = 'https://i0.hdslb.com/bfs/archive/31776d5db2723677939430797305451b7f3db2ae.jpg'
    }

    // 默认昵称
    if (!nickName) {
      nickName = "暂无昵称"
    }
    if (!mobile) {
      return "手机号不能为空"
    }

    // 判断账号密码是否为空
    if (!account || !password) {
      return "账号或密码不能为空"
    }

    // 判断是否选择角色
    if (roleId===undefined||roleId==="") {
      return "请选先选择身份"
    } else {
      if (roleId == 1 && !userId) {
        return "请输入教师工号"
      } else if (roleId == 2 && !userId) {
        return "请输入学生学号"
      } else if (roleId == 1 && userId) {
        // 先查询是否已经有账号了
        let usert = await mysql.get('user', { userId })
        if (!usert) {
          // 查询教师表是否有该教师
          let teacher = await mysql.get('teacher', { teacherId: userId })
          if (!teacher) {
            return "该教师不存在"
          } else {
            // 将教师数据存入user表中
            let res = await mysql.insert('user', { userId, account, password, nickName, avatar, roleId, mobile })
            return "注册成功"
          }
        } else {
          return "该教师已有账号"
        }
      } else if (roleId === 2 && userId) {
        // 先查询是否已经有账号了
        let users = await mysql.get('user', { userId })
        if (!users) {
          // 查询学生表是否有该学生
          let student = await mysql.get('student', { studentId: userId })
          if (!student) {
            return "该学生不存在"
          } else {
            // 将学生数据存入user表中
            let res = await mysql.insert('user', { userId, account, password, nickName, avatar, roleId, mobile })
            return "注册成功"
          }
        } else {
          return "该学生已有账号"
        }
      }
      else if (roleId === 0 && userId) {
        // 先查询是否已经有账号了
        let users = await mysql.get('user', { userId })
        if (!users) {
          // 查询管理员表
          let admin = await mysql.get('admin', { adminId: userId })
          if (!admin) {
            return "该管理员不存在"
          } else {
            // 将管理员数据存入user表中
            let res = await mysql.insert('user', { userId, account, password, nickName, avatar, roleId, mobile })
            return "注册成功"
          }
        } else {
          return "该管理员已有账号"
        }
      }
    }


  }
  // 检验账号唯一性
  async checkoutAccountOnly(account) {
    let { mysql } = this.app

    let accountInfo = await mysql.get('user', { account })
    if (accountInfo) {
      // 账号不唯一
      return false
    } else {
      // 账号唯一
      return true
    }
  }
  // 获取用户全部信息
  async getUserInfo(id, roleId) {
    let { mysql } = this.app
    let accountInfo = await mysql.get('user', { userId: id })
    let userInfo = {}
    let obj = {}
    if (accountInfo) {

      if (roleId == 0) {
        userInfo = await mysql.get('admin', { adminId: id })
        if (!userInfo) {
          obj.message = "该管理员不存在"
          return obj
        } else {
          obj = { ...accountInfo }
          obj.message = "信息查询成功"

          obj.name = userInfo.admName
          obj.age = userInfo.admAge
          obj.gender = userInfo.admGender
          return obj
        }


      } else if (roleId == 1) {
        userInfo = await mysql.get('teacher', { teacherId: id })
        if (!userInfo) {
          obj.message = "该教师不存在"
          return obj
        } else {
          obj = { ...accountInfo }
          obj.message = "信息查询成功"

          obj.name = userInfo.teachName
          obj.age = userInfo.teachAge
          obj.gender = userInfo.teachGender
          return obj
        }


      } else if (roleId == 2) {
        userInfo = await mysql.get('student', { studentId: id })
        if (!userInfo) {
          obj.message = "该教师不存在"
          return obj
        } else {

          obj = { ...accountInfo }
          obj.message = "信息查询成功"
          obj.name = userInfo.stuName
          obj.age = userInfo.stuAge
          obj.gender = userInfo.stuGender
          return obj
        }

      }
    }
    else {
      obj.message = "不存在该用户"
      return obj
    }


  }

  // 重置用户密码
  async resetPassword(userId) {
    let { mysql } = this.app
    const options = {
      where: {
        userId
      }
    }
    let res = await mysql.update('user', { password: 'user123@' }, options)
    // console.log(userId, newPsd);
    // console.log(res);
    if (res.affectedRows == 1) {

      return "重置成功"
    } else {
      return "重置失败无此用户"
    }
  }
  // 更新用户信息
  async updateUserInfo(userInfo) {
    let { mysql } = this.app
    let { userId, nickName, avatar, mobile } = userInfo
    let options = {
      where: {
        userId: userId
      }
    }
    let result = {}

    // console.log(res);
    if (!nickName && !avatar && !mobile) {
      return "更新成功"
    } else if (!nickName) {
      result = await mysql.update('user', { avatar, mobile }, options)
    } else if (!avatar) {
      result = await mysql.update('user', { nickName, mobile }, options)
    } else if (!mobile) {
      result = await mysql.update('user', { nickName, avatar }, options)
    } else if (!nickName && !avatar) {
      result = await mysql.update('user', { mobile }, options)
    } else if (!nickName && mobile) {
      result = await mysql.update('user', { avatar }, options)
    } else if (!avatar && !mobile) {
      result = await mysql.update('user', { nickName }, options)
    } else {
      result = await mysql.update('user', { nickName, avatar, mobile }, options)

    }
    if (result.affectedRows == 1) {
      return "更新成功"
    } else {
      return "更新失败"
    }
  }
  // 更新用户密码
  async updatePassword(userId, password,newpsd) {
    let { mysql } = this.app
    let user = await  mysql.get('user',{userId})
    if(user){
      if(user.password == password){
        let options = {
          where: {
            userId
          }
        }
        let res = await mysql.update('user', { userId, password:newpsd }, options)
        if (res.affectedRows == 1) {
    
          return "修改成功"
        } else {
          return "修改失败"
        }
      }else{
        return "原密码错误"
      }
    }else{
      return "系统无该用户"
    }

  }
  // 获取用户收藏的实验室列表
  async getUserCollect(userId, labName, typeId) {
    let { mysql } = this.app
    let obj = {}
    if (typeId) {
      typeId = parseInt(typeId)
    }

    if (!typeId) {
      let sql = `select * from laboratory where labname like ? and laboratoryId in(select laboratoryId from collect where userId = ?)`
      let sql2 = `select count(*) total from laboratory where labname like ? and laboratoryId in(select laboratoryId from collect where userId = ?)`
      let res = await mysql.query(sql, ['%' + labName + '%', userId])
      let res2 = await mysql.query(sql2, ['%' + labName + '%', userId])
      // console.log(res2);
      obj.list = [...res]
      obj.total = res2[0].total
    } else {
      let sql = `select * from laboratory where labname like ? and typeId = ? and laboratoryId in(select laboratoryId from collect where userId = ?)`
      let sql2 = `select count(*) total from laboratory where labname like ? and typeId = ? and laboratoryId in(select laboratoryId from collect where userId = ?)`
      let res = await mysql.query(sql, ['%' + labName + '%', typeId, userId])
      let res2 = await mysql.query(sql2, ['%' + labName + '%', typeId, userId])
      // console.log(res2);

      obj.list = [...res]
      obj.total = res2[0].total
    }

    let arr = [...obj.list]
    for (let i = 0; i < arr.length; i++) {
      let result = await mysql.get('labtype', { typeId: arr[i].typeId })
      arr[i].typeName = result.typeName
    }
    obj.list = [...arr]

    return obj

  }

  // 获取用户预约列表
  async getUserRes(userId,status,labName,dateTime,reservationId,type) {
    let { mysql } = this.app
    let obj = {}
    if(!status){
      let sql = `select * from reservation where userId = ?`
      let sql1 = `select count(*) total from reservation where userId = ?`
      let res = await mysql.query(sql, [userId])
      let res1 = await mysql.query(sql1, [userId])
      obj.list = res
      obj.total = res1[0].total
    }else{
      status = parseInt(status)
      let sql = `select * from reservation where userId = ? and status = ?`
      let sql1 = `select count(*) total from reservation where userId = ? and status = ?`
      let res = await mysql.query(sql, [userId,status])
      let res1 = await mysql.query(sql1, [userId,status])
      obj.list = res
      obj.total = res1[0].total
    }

    let arr = [...obj.list]
    for(let i=0; i<arr.length;i++){
        let sql1 = `select datetime from daytime where timeId = ?`
        let resDateTime = await mysql.query(sql1,[arr[i].dayTimeId])
       arr[i].dateTime = resDateTime[0].datetime
        let sql2 = `select * from timeoption where timeId in (select timeOpId from daytime where timeId in (select dayTimeId from reservation where reservationId=?))`
        let resTimeOp = await mysql.query(sql2,[arr[i].reservationId])
        arr[i].timeOption = resTimeOp[0]
        let sql3 = `select * from laboratory where laboratoryId in (select laboratoryId from  timeoption where timeId in (select timeOpId from daytime where timeId = ?  ) )`
        let  resLab = await mysql.query(sql3,[arr[i].dayTimeId])
        arr[i].lab = resLab[0]
    }
    
    if(!labName){
      obj.list = [...arr]
    }else{
      let arr1 = [...arr]
      let arr2 = []
      arr1.forEach((item,index)=>{
        let str = item.lab.labName

        if(str.includes(labName)){
          arr2.push(item)
        }
   
      })
      obj.total = arr2.length
      obj.list = [...arr2]
    }
    let arr3 = []
    if(dateTime){
      let arr = [ ...obj.list]
      arr.forEach((item,index)=>{
        if(item.dateTime==dateTime){
          arr3.push(item)
        }
      })
      obj.total = arr3.length
      obj.list = [...arr3]

    }
    if(reservationId){
      let arr = [ ...obj.list]
      let arr4 = []
      arr.forEach((item,index)=>{
        if(item.reservationId==reservationId){
          arr4.push(item)
        }
      })
      obj.total = arr4.length
      obj.list = [...arr4]
    }
    if(type){
      let arr = [ ...obj.list]
      let arr4 = []
      arr.forEach((item,index)=>{
        if(item.type==type){
          arr4.push(item)
        }
      })
      obj.total = arr4.length
      obj.list = [...arr4]
    }

  

  
    
    return obj
  }

  //  条件获取用户列表
  async getUsers(userId,userName,roleId,searchRole){
    let {mysql} = this.app
    let arrtemp = []

    if(roleId==-1){
      //  超级管理员可以查所有用户包括管理员
      let sql = `select * from user where roleId != ?`
      let users = await mysql.query(sql,[-1])
      let arr = [...users]
      arrtemp = [...arr]

    }else{
      // 管理员只能查用户
      let sql = `select * from user where roleId != ?`
      let users = await mysql.query(sql,[-1])
      let arr = [...users]
      let arr1 = []
      arr.forEach((item,index)=>{
        if(item.roleId!=0&item.roleId!=-1){
          arr1.push(item)
        }
      })
      arrtemp = [...arr1]

    }
    // 如果有要查用户类型的，有传入类型searchRole
    if(searchRole!==undefined&searchRole!==""){
      let roleId = searchRole
      let arr = []
      arrtemp.forEach((item,index)=>{
        if(item.roleId==roleId){
          arr.push(item)
        }
      })
      arrtemp = [...arr]
    }

    // 查出每一位用户的真实信息
    for(let i=0;i<arrtemp.length;i++){
        let roleId = arrtemp[i].roleId
        let userId = arrtemp[i].userId
        let obj = {}
        if (roleId == 0) {
          let admin = await mysql.get('admin', { adminId: userId })
          obj.id = admin.adminId
          obj.name = admin.admName
          obj.age = admin.admAge
          obj.gender = admin.admGender
        } else if (roleId == 1) {
          let teacher = await mysql.get('teacher', { teacherId: userId })
          obj.id = teacher.teacherId
          obj.name = teacher.teachName
          obj.age = teacher.teachAge
          obj.gender = teacher.teaGender
        } else if (roleId == 2) {
          let student = await mysql.get('student', { studentId: userId })
          obj.id = student.studentId
          obj.name = student.stuName
          obj.age = student.stuAge
          obj.gender = student.stuGender
        }
        arrtemp[i].userInfo = {...obj}
    }
    // console.log(arrtemp);
    let lastArr = []
    if(userName||userId){
      if(userName){
        let arr = []
        arrtemp.forEach((item,index)=>{
          let str = item.userInfo.name
          if(str.includes(userName)){
            arr.push(item)
          }
        })
        lastArr = [...arr]
      }
      if(userId){
        let arr = []
        arrtemp.forEach((item,index)=>{
          if(userId==item.userId){
            arr.push(item)
          }
        })
        lastArr = [...arr]
      }
    }else{
      lastArr = [...arrtemp]
    }

   
    return lastArr

  }

  //  条件查询出基础用户数据
async  getBaseUsers(searchRole,userName,userId){
  
  let {mysql} = this.app
  let sql1 = `select * from admin`
  let sql2 = `select * from teacher`
  let sql3 = `select * from student`
  let users1 = await mysql.query(sql1)
  let users2 = await mysql.query(sql2)
  let users3 = await mysql.query(sql3)
  // 总数据数组
  let arr = []
  users1.forEach((item,index)=>{
    let obj = {}
    obj.userId = item.adminId
    obj.userName = item.admName
    obj.age = item.admAge
    obj.gender = item.admGender
    obj.roleId = 0
    arr.push(obj)
  })
  users2.forEach((item,index)=>{
    let obj={}
    obj.userId = item.teacherId
    obj.userName = item.teachName
    obj.age = item.teachAge
    obj.gender = item.teaGender
    obj.roleId = 1
    arr.push(obj)
  })
  users3.forEach((item,index)=>{
    let obj={}
    obj.userId = item.studentId
    obj.userName = item.stuName
    obj.age = item.stuAge
    obj.gender = item.stuGender
    obj.roleId = 2
    arr.push(obj)
  })

  // 给所有数据做个判断，是否已经注册有账号
  for(let i=0;i<arr.length;i++){
    let userId = arr[i].userId
    let info = await mysql.get('user',{userId})
    if(info){
      arr[i].isRegister = true
    }else{
      arr[i].isRegister = false
    }
  }



  if(searchRole===undefined||searchRole===""){


  }else{

    let arr1 = []
    arr.forEach((item,index)=>{
      if(item.roleId==searchRole){
        arr1.push(item)
      }
    })

    arr = [...arr1]
   
  }

  if(userName){
    let arr3 = []
    arr.forEach((item,index)=>{
      let str = item.userName
      if(str.includes(userName)){
        arr3.push(item)
      }
    })
    arr = [...arr3]
  }

  if(userId){
    let arr3 = []
    arr.forEach((item,index)=>{
      if(userId==item.userId){
        arr3.push(item)
      }
    })
    arr = [...arr3]
  }

  return arr
}

// 根据id删除用户
  async deleteUser(userId){
    let {mysql} = this.app
    //  先删除用户的账号
    let delAccount = await mysql.delete('user',{userId})
    // 然后删除用户相应表中的数据,由于不知道是哪个身份的用户，所以每个表我都删一遍
    let delUser1 = await mysql.delete('admin',{adminId:userId})
    let delUser2 = await mysql.delete('teacher',{teacherId:userId})
    let delUser3 = await mysql.delete('student',{studentId:userId})
    // 同时删除掉用户相关的预约记录，防止报错
    let resDel = await mysql.delete('reservation',{userId})

    return "删除成功"


  }
  //  单个添加基础用户
  async addBaseUsers(userId,userName, age,gender,roleId,type){
    let {mysql} = this.app
    console.log(type);
    if(type==1){

      let usrInfo = await mysql.get('user',{userId:userId})
      if(usrInfo){
        return "该用户已存在"
      }
      if(roleId===0){
        
        // 先查这个管理员是否已经存在
        let adInfo = await mysql.get('admin',{adminId:userId})
        if(adInfo){
          return "该用户已存在"
        }else{
          let res = await mysql.insert('admin', { adminId:userId, admName:userName, admAge:age, admGender:gender })
          return "添加成功"
        }
        
      }else if(roleId ==1){

              // 先查这个教师是否已经存在
              let teaInfo = await mysql.get('teacher',{teacherId:userId})
              if(teaInfo){
                return "该用户已存在"
              }else{
       
                let res = await mysql.insert('teacher', { teacherId:userId, teachName:userName, teachAge:age, teaGender: gender})
                return "添加成功"
              }
  
      }else if(roleId ==2){
              // 先查这个学生是否已经存在
              let stuInfo = await mysql.get('student',{studentId:userId})
              if(stuInfo){
                return "该用户已存在"
              }else{
                let res = await mysql.insert('student', { studentId:userId, stuName:userName, stuAge:age, stuGender:gender })
                return "添加成功"
              }
      }
    }else if(type == 2){
     
      // 更新
      if(roleId===0){

       let options = {
        where:{
          adminId:userId
        }
       }
       let res = await mysql.update('admin', { admName:userName, admAge:age, admGender:gender },options)
       return "更新成功"
        
      }else if(roleId ===1){
        let options = {
          where:{
            teacherId:userId
          }
         }
         let res = await mysql.update('teacher', {teachName:userName, teachAge:age, teaGender: gender},options)
         return "更新成功"
  
      }else if(roleId ==2){
        let options = {
          where:{
            studentId:userId
          }
         }
         let res = await mysql.update('student', { stuName:userName, stuAge:age, stuGender:gender },options)
         return "更新成功"
      }
      
    }


  }


}


module.exports = UserService